package top.milkbox.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import top.milkbox.info.HttpToHttpsInfo;

/**
 * 让http请求自动转为https请求
 */
@Slf4j
public class HttpAndHttpsConfiguration {


    /**
     * 编程方式实现springboot的http
     *
     * @return
     */
    @ConditionalOnProperty(value = {"info.https-pass"}) // 当info.https-pass为true的时候加载
    @Bean
    public TomcatServletWebServerFactory servletContainer(
            @Autowired HttpToHttpsInfo httpToHttpsInfo
    ) {
        log.info("开启http转https");
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                //安全约束
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(createHttpConnector(httpToHttpsInfo));
        log.info("http端口：" + httpToHttpsInfo.getHttpPort() +
                "  将会自动转为https端口：" + httpToHttpsInfo.getHttpsPort());
        return tomcat;
    }

    /**
     * 创建http连接器
     *
     * @return
     */
    private Connector createHttpConnector(HttpToHttpsInfo httpToHttpsInfo) {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        // http端口
        connector.setPort(httpToHttpsInfo.getHttpPort());
        connector.setSecure(false);
        // https端口
        connector.setRedirectPort(httpToHttpsInfo.getHttpsPort());
        return connector;
    }

}
